package com.cqjtu.eecs.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cqjtu.eecs.entity.TeachClass;
import com.cqjtu.eecs.entity.dto.TeacherDto;
import com.cqjtu.eecs.exception.ParamsErrorException;
import com.cqjtu.eecs.service.IAssessmentLinkService;
import com.cqjtu.eecs.service.ICourseGoalScoreService;
import com.cqjtu.eecs.service.ITeachClassService;
import com.cqjtu.eecs.service.ITeachClassStudentService;
import com.cqjtu.eecs.utils.Assert;
import com.cqjtu.eecs.utils.Result;
import com.cqjtu.eecs.utils.ResultCode;
import com.cqjtu.eecs.utils.listener.NoModelDataListener;
import com.cqjtu.eecs.utils.listener.TeacherListener;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 教学班 前端控制器
 * </p>
 *
 * @author    
 * @since 2022-03-07
 */
@RestController
@RequestMapping("/teach-class")
@Api(tags = "教学班管理接口")
public class TeachClassController {

    @Autowired
    private ITeachClassService teachClassService;

    @Autowired
    private ITeachClassStudentService teachClassStudentService;

    @Autowired
    private IAssessmentLinkService assessmentLinkService;

    @Autowired
    private ICourseGoalScoreService courseGoalScoreService;

    @PostMapping("/score-import/{grade}/{courseName}/{teacherCode}/{teachClassName}")
    @ApiOperation(value = "成绩录入", notes = "grade-年级, courseName-课程名称, teacherCode-授课教师工号, teachClassName-教学班名")
    @Transactional(rollbackFor = Exception.class)
    public Result studentScoreImport(@PathVariable Integer grade, @PathVariable String courseName
                                     , @PathVariable String teachClassName, @PathVariable String teacherCode,
                                     @RequestBody MultipartFile file) {
        if (Objects.isNull(file))
            return Result.error(ResultCode.PARAMETER_ERROR);
        Assert.notNull(grade, new ParamsErrorException("年级不能为空"));
        Assert.notBlank(courseName, new ParamsErrorException("课程名不能为空"));
        Assert.notBlank(teacherCode, new ParamsErrorException("授课教师工号不能为空"));
        Assert.notBlank(teachClassName, new ParamsErrorException("教学班名不能为空"));

        // 创建教学班并返回教学班编号
        Integer tcId = teachClassService.insertTeachClass(courseName, teachClassName, teacherCode);
        if (tcId == null)
            return Result.error();
        try {
            NoModelDataListener dataListener = new NoModelDataListener();
            EasyExcel.read(file.getInputStream(), dataListener)
                    .sheet().doRead();

            // 所有学生成绩信息
            List<Map<Integer, String>> dataList = dataListener.getDataList();
            // excel头部信息
            Map<Integer, String> headMap = dataListener.getHeadMap();

            // 插入教学班中所有的学生
            boolean insertStudent = teachClassStudentService.insertTeacherClassStudent(tcId, dataList);
            // 插入教学班学生失败 回滚
            if (!insertStudent) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return Result.error();
            }

            // 插入学生各个考核环节成绩
            boolean insertAssessmentLink = assessmentLinkService.insertStudentAssessmentLink(grade, courseName, tcId, dataList, headMap);
            // 插入学生考核环节成绩失败 回滚
            if (!insertAssessmentLink) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return Result.error();
            }

            // 计算课程目标达成度
            boolean cal = courseGoalScoreService.calculateAndSave(grade, courseName, tcId, headMap, dataList);
            // 插入考核环节成绩失败 回滚
            if (!cal) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return Result.error();
            }
        } catch (IOException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error();
        }
        return Result.success();
    }

    @GetMapping("/teach-class-info/{name}")
    @ApiOperation(value = "根据教学班名获取教学班信息")
    public TeachClass getTeacherClassInfoByName(@PathVariable String name) {
        try {
            TeachClass tc = teachClassService.getOne(new QueryWrapper<TeachClass>().eq("tc_name", name));
            return tc;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
